/* -*- coding: utf-8; tab-width: 4 -*-
vim: ts=4 noet ai */

/**
	Desktopd Rainbow Persona -- Colorful Firefox

	Copyright © 2016  Desktopd Project

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

	@license GPL-3.0+
	@file
*/

'use strict';

const unload = require ('sdk/system/unload');
const {LightweightThemeManager} = require ('resource://gre/modules/LightweightThemeManager.jsm');

const YCbCr = require ('./colors/YCbCr');
let usedId = void 0;
let current;

const changeRGB = (r, g, b) => {
	const persona = {
		headerURL: 'data:image/svg+xml,<svg%20xmlns="http://www.w3.org/2000/svg"/>'
		, footerURL: 'data:image/svg+xml,<svg%20xmlns="http://www.w3.org/2000/svg"/>'
		, iconURL: 'resource://rainbow-persona/icon.png'
		, author: 'Rainbow Persona'
	};
	
	[r, g, b] = [r, g, b].map (x => Math.min (1, Math.max (0, x)));
	persona.name = `(R, G, B) = (${r.toFixed (4)}, ${g.toFixed (4)}, ${b.toFixed (4)})`;
	persona.accentcolor = '#' + [r, g, b].map (x =>
		('0' + Math.min (0xff, Math.floor (x * 0x100)).toString (0x10)).substr (-2))
		.join ('');
	persona.textcolor = YCbCr.fromRGB (r, g, b)[0] < 128 ? '#fff' : '#000';
	
	const oldId = usedId;
	persona.id = usedId = 'rainbow-' + Math.random ();
	
	LightweightThemeManager.themeChanged (persona);
	current = [r, g, b];
	if (oldId) {
		LightweightThemeManager.forgetUsedTheme (oldId);
	}
};

const getCurrent = () => current;

unload.when (aReason => {
	if (usedId) {
		LightweightThemeManager.forgetUsedTheme (usedId);
	}
});

exports.changeRGB = changeRGB;
exports.getCurrent = getCurrent;

